package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RemoveOpenGameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // remove Open games that have been closed (a user closes a game they opened)
        System.out.println("RemoveOpenGameServlet: starting");
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
     //   int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];

        Game game = new Game();
        try {
            game = user.oldOpenGames.take();
            if (!user.online) {
                return;
            }
        } catch (InterruptedException e) {
            System.out.println("RemoveOpenGamesServlet InterruptedException: " + e.getMessage());
        }
        int playerID = game.player1ID;

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print(playerID);
        out.close();
        System.out.println("removeOpenGamesServlet: player with id " + playerID);
        System.out.println("RemoveOpenGameServlet: finished");
    }
}
